package com.chefu.common.net.file.upload;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.FileNameMap;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import okhttp3.FormBody;
import okhttp3.Headers;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * Created by ${wangshuyun} on 2016/11/14 0014.
 *
 * <p>
 * 自定义 form 表单提交
 */
public class PostFormRequest {

    private List<FileInputEntity> files;

    //参数
    private Map<String, String> params;


    public PostFormRequest(Map<String, String> params) {
        this.params = params;
    }

    /**
     * 创建 RequestBody
     *
     * @return
     */
    public RequestBody buildRequestBody() {
        if (files == null || files.isEmpty()) {
            FormBody.Builder builder = new FormBody.Builder();
            addParams(builder);
            return builder.build();
        } else {
            MultipartBody.Builder builder = new MultipartBody.Builder()
                    .setType(MultipartBody.FORM);
            addParams(builder);

            for (int i = 0; i < files.size(); i++) {
                FileInputEntity inputEntity = files.get(i);

                RequestBody fileBody = RequestBody.create(MediaType.parse(guessMimeType(inputEntity.getFilename())), inputEntity.getFile());
                builder.addFormDataPart(inputEntity.getKey(), inputEntity.getFilename(), fileBody);
            }
            return builder.build();
        }
    }

    /**
     * 添加上传参数
     *
     * @param builder
     */
    private void addParams(FormBody.Builder builder) {
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }

    /**
     * 添加上传参数
     *
     * @param builder
     */
    private void addParams(MultipartBody.Builder builder) {
        if (params != null && !params.isEmpty()) {
            for (String key : params.keySet()) {
                builder.addPart(Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""),
                        RequestBody.create(null, params.get(key)));
            }
        }
    }

    /**
     * 添加多个file
     *
     * @param key
     * @param files
     */
    public void addFiles(String key, Map<String, File> files) {
        for (String filename : files.keySet()) {
            this.files.add(new FileInputEntity(key, filename, files.get(filename)));
        }
    }

    /**
     * 添加file
     *
     * @param name
     * @param filename
     * @param file
     */
    public void addFile(String name, String filename, File file) {
        this.files.add(new FileInputEntity(name, filename, file));
    }

    /**
     * 格式化请求
     *
     * @param path
     * @return
     */
    private String guessMimeType(String path) {
        FileNameMap fileNameMap = URLConnection.getFileNameMap();
        String contentTypeFor = null;
        try {
            contentTypeFor = fileNameMap.getContentTypeFor(URLEncoder.encode(path, "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        if (contentTypeFor == null) {
            contentTypeFor = "application/octet-stream";
        }
        return contentTypeFor;
    }

    public void addParams(Map<String, String> params) {
        this.params = params;
    }

    public void addParams(String key, String val) {
        if (this.params == null) {
            params = new LinkedHashMap<>();
        }
        params.put(key, val);
    }


}
